#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
#include<vector>
#include<queue>
using namespace std;
struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {}
};
class Solution {
public:
    vector<vector<int>> levelOrder_v1(TreeNode* root)
    {
        queue<TreeNode*> q;
        int levelSize = 0;
        if (root)
        {
            q.push(root);
            levelSize = 1;
        }
        vector<vector<int>> vv;
        while (!q.empty())
        {
            vector<int> v;
            while (levelSize--)
            {
                TreeNode* front = q.front();
                q.pop();
                v.push_back(front->val);
                if (front->left)
                    q.push(front->left);
                if (front->right)
                    q.push(front->right);
            }
            levelSize = q.size();
            vv.push_back(v);
        }
        return vv;
    }
    vector<vector<int>> levelOrder_v2(TreeNode* root)
    {
        queue<TreeNode*> q;
        queue<int> levelq;
        vector<vector<int>> vv;
        if (root)
        {
            q.push(root);
            levelq.push(0);
        }
        while (!q.empty())
        {
            TreeNode* qfront = q.front();
            int Lfront = levelq.front();

            q.pop();
            levelq.pop();

            if (vv.size() < Lfront)
            {
                vv.push_back(vector<int>());
            }

            vv[Lfront].push_back(qfront->val);

            if (qfront->left)
            {
                q.push(qfront->left);
                levelq.push(Lfront + 1);
            }
            if (qfront->right)
            {
                q.push(qfront->right);
                levelq.push(Lfront + 1);
            }
        }
        return vv;
    }
};
int main()
{
    Solution s;
    TreeNode n1(3);
    TreeNode n2(9);
    TreeNode n3(20);
    TreeNode n4(15);
    TreeNode n5(17);
    n1.left = &n2;
    n1.right = &n3;
    n2.left = nullptr;
    n2.right = nullptr;
    n3.left = &n4;
    n3.right = &n5;
    n4.left = nullptr;
    n4.right = nullptr;
    n5.left = nullptr;
    n5.right = nullptr;
    s.levelOrder_v2(&n1);
    return 0;
}